<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>PDF Creator</title>

    <script src="{{ url_for('static', filename='js/vue.global.prod.js') }}"></script>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/index.min.css') }}"/>
    <script src="{{ url_for('static', filename='js/index.full.js') }}"></script>

    <!-- 添加这一行 -->
    <script src="{{ url_for('static', filename='js/zh-cn.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/clipboard.min.js') }}"></script>

</head>

{% raw %}

    <body>
    <div id="app">
        <!-- 添加登录框 -->
        <div v-if="!isLoggedIn" class="login-container">
            <el-card class="login-card">
                <template #header>
                    <h2>登录</h2>
                </template>
                <el-form>
                    <el-form-item label="用户名">
                        <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
                    </el-form-item>
                    <el-form-item label="密码">
                        <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleLogin">登录</el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>

        <!-- 将原有内容包装在条件渲染中 -->
        <el-container v-if="isLoggedIn">
            <el-main>
                <el-card style="margin-bottom: 10px">
                    <template #header>
                        <h2>上传 Excel 文件</h2>
                    </template>
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <el-upload
                                action="/upload_excel"
                                :auto-upload="true"
                                :show-file-list="true"
                                :on-success="handleUploadSuccess"
                                :on-error="handleUploadError"
                                accept=".xlsx,.xls">
                            <el-button type="primary">点击上传</el-button>
                            <template #tip>
                                <div class="el-upload__tip">只能上传 xlsx/xls 文件</div>
                            </template>
                        </el-upload>
                        <el-button type="success" @click="downloadTemplate">
                            下载模板
                        </el-button>
                    </div>
                </el-card>

                <el-card class="table-card">
                    <template #header>
                        <el-button type="primary" @click="loadPdfData">
                            刷新
                        </el-button>
                        <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length">
                            批量删除
                        </el-button>
                        <el-button type="success" @click="handleBatchDownload" :disabled="!selectedRows.length">
                            批量下载
                        </el-button>
                    </template>
                    <el-table style="width: 100%"
                              :data="pdfList"
                              @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55"></el-table-column>
                        <el-table-column prop="id" label="序号" width="80"></el-table-column>
                        <el-table-column prop="create_time" label="创建时间" ></el-table-column>

                        <el-table-column prop="notify_name" label="通知人" ></el-table-column>
                        <el-table-column prop="company" label="公司" ></el-table-column>
                        <el-table-column prop="deadline" label="截至日期" ></el-table-column>
                        <el-table-column prop="office" label="事务所" ></el-table-column>
                        <el-table-column prop="date" label="日期" ></el-table-column>
                        <el-table-column prop="phone" label="电话" ></el-table-column>
                        <el-table-column prop="lawyer" label="律师" ></el-table-column>


                        <el-table-column label="PDF预览" width="120" fixed="right">
                            <template #default="scope">
                                <span v-if="!scope.row.pdf_file_0">生成中</span>
                                    <template v-else>
                                <el-link  :href="HOST + scope.row.pdf_file_0" target="_blank">资方</el-link>
                                        &nbsp;&nbsp;
                                <el-link  :href="HOST + scope.row.pdf_file_1" target="_blank">自营</el-link>
                                        </template>
                            </template>
                        </el-table-column>
                        <el-table-column label="复制链接" width="120" fixed="right">
                            <template #default="scope">
                                <span v-if="!scope.row.pdf_file_0">生成中</span>
                                <template v-else>
                                    <el-button class="copy-btn" 
                                              type="primary" 
                                              link 
                                              :data-clipboard-text="HOST + scope.row.pdf_file_0">
                                        资方
                                    </el-button>
                                    <el-button class="copy-btn" 
                                              type="primary" 
                                              link 
                                              :data-clipboard-text="HOST + scope.row.pdf_file_1">
                                        自营
                                    </el-button>
                                </template>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="pagination-container">
                        <el-pagination
                                v-model:current-page="currentPage"
                                v-model:page-size="pageSize"
                                :page-sizes="[10, 20, 50, 100,500,1000]"
                                layout="total, sizes, prev, pager, next"
                                :total="total"
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                        />
                    </div>
                </el-card>
            </el-main>
        </el-container>


    </div>
{% endraw %}
</body>

<script>
    const {createApp} = Vue;


    const app = createApp({
        data() {
            return {
                HOST: 'https://o.weiquan365.com/',
                pdfList: [],
                currentPage: 1,
                pageSize: 10,
                total: 0,
                isLoggedIn: localStorage.getItem('login') === '1',
                loginForm: {
                    username: '',
                    password: ''
                },
                clipboard: null,
                selectedRows: []
            };
        },
        methods: {
            async loadPdfData() {
                try {
                    const response = await fetch(`/pdf_data?page=${this.currentPage}&per_page=${this.pageSize}`);
                    const result = await response.json();
                    this.pdfList = result.data;
                    this.total = result.total;
                    this.$message.success('刷新成功');
                } catch (error) {
                    this.$message.error('加载 PDF 数据失败');
                }
            },
            handleSizeChange(val) {
                this.pageSize = val;
                this.loadPdfData();
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.loadPdfData();
            },
            handleUploadSuccess() {
                this.$message.success('上传成功');
                this.loadPdfData();
            },
            handleUploadError() {
                this.$message.error('上传失败');
            },
            initClipboard() {
                this.clipboard = new ClipboardJS('.copy-btn');
                
                this.clipboard.on('success', (e) => {
                    this.$message.success('复制成功：' + e.text);
                    e.clearSelection();
                });
                
                this.clipboard.on('error', () => {
                    this.$message.error('复制失败');
                });
            },
            async handleLogin() {
                try {
                    const response = await fetch('/login', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(this.loginForm)
                    });
                    const result = await response.json();
                    
                    if (result.success) {
                        this.isLoggedIn = true;
                        localStorage.setItem('login', '1');
                        this.loadPdfData();
                    } else {
                        this.$message.error('登录失败');
                    }
                } catch (error) {
                    this.$message.error('登录失败');
                }
            },
            async handleBatchDelete() {
                try {
                    // 添加确认对话框
                    const confirmResult = await this.$confirm(
                        `确定要删除选中的 ${this.selectedRows.length} 条记录吗？`,
                        '警告',
                        {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }
                    ).catch(() => {
                        // 用户点击取消
                        return false;
                    });

                    if (!confirmResult) {
                        return;
                    }

                    const ids = this.selectedRows.map(row => row.id);
                    const response = await fetch('/batch_delete', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ ids })
                    });
                    const result = await response.json();
                    if (result.success) {
                        this.$message.success('删除成功');
                        this.loadPdfData();
                    } else {
                        this.$message.error('删除失败');
                    }
                } catch (error) {
                    this.$message.error('删除失败');
                }
            },
            handleSelectionChange(rows) {
                this.selectedRows = rows;
            },
            async downloadTemplate() {
                try {
                    const response = await fetch('/download_template');
                    if (!response.ok) {
                        throw new Error('下载失败');
                    }
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = 'template.xlsx';
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                } catch (error) {
                    this.$message.error('下载模板失败');
                }
            },
            async handleBatchDownload() {
                try {
                    const ids = this.selectedRows.map(row => row.id);
                    const response = await fetch('/batch_download', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ ids })
                    });
                    
                    if (!response.ok) {
                        throw new Error('下载失败');
                    }
                    
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = '批量下载.zip';
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                    
                    this.$message.success('下载成功');
                } catch (error) {
                    this.$message.error('下载失败');
                }
            }
        },
        mounted() {
            if (this.isLoggedIn) {
                this.loadPdfData();
                this.initClipboard();
            }
        },
        beforeUnmount() {
            if (this.clipboard) {
                this.clipboard.destroy();
            }
        }
    });

    app.use(ElementPlus, {
        locale: ElementPlusLocaleZhCn
    }).mount('#app');

</script>

<style>
    .pagination-container {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
    }
    
    .login-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
    }
    
    .login-card {
        width: 400px;
    }
</style>
</html>
